<?php

namespace Controller\Upload;

class Image extends \Controller\Base {

	public function actionIndex() {
		//上传配置
		$path = '../../Web/htdocs/upload/';
		$config = array(
			'savePath' => $path ,             //存储文件夹
			'maxSize' => 102400 * 20 ,                   //允许的文件最大尺寸，单位KB
			'allowFiles' => array( '.gif' , '.png' , '.jpg' , '.jpeg' , '.bmp' )  //允许的文件格式
		);
        $upfile = '';
        foreach($_FILES as $key => $val){
            $upfile = $key;
        }
		//上传文件目录
		$up = new \Util\Uploader($upfile, $config );
		$info = $up->getFileInfo();
		$error = $info['state'];
		if ($error != 'SUCCESS') {
			$this->responseError($error);
		}
		$file = $info['url'];
		$up->cutImage($file, 600);
		$file = $this->getFileName($file, 600);
		$http = \Entity\Domain::instance()->www;
        $src = $http . '/upload/' . str_replace($path, '', $file);
        $url = $http . '/upload/' . str_replace($path, '', $info['url']);
		$this->response($src, $url);
	}

	private function response($src, $url) {
		$data = array(
			'error' => 0,
			'src' => $src,
			'message' => '上传成功',
            'url' => $url
        );
		$callback = $this->getParam('callback');//jsonp回调
		if($callback) {
			echo $callback.'('.json_encode($data).')';
		} else {
			echo json_encode($data);
		}
		\Main::sysExit();
        exit;
	}

	private function responseError($msg, $code = 1) {
		$data = array(
			'error' => $code,
			'data' => '',
			'message' => $msg,
		);
		$callback = $this->getParam('callback');//jsonp回调
		if($callback) {
			echo $callback.'('.json_encode($data).')';
		} else {
			echo json_encode($data);
		}
		\Main::sysExit();
        exit;
	}

	private function getFileName($photo, $width) {
		$pathInfo = pathinfo($photo);
		$nowFile =  '/' . $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '_' . $width . '.' . $pathInfo['extension'];
		return $nowFile;
	}
}